<template>
  <div class="login-wrap">
    <el-card class="container">
      <div slot="header" class="login-title">个人博客后台管理系统</div>
      <!-- <div class="avatar-box">
        <img src="../assets/images/avatar1.jpg" alt="" />
      </div> -->
      <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名:" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密　码:" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            clearable
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    login() {
      {
        // 校验表单
        this.$refs.loginForm.validate((valid) => {
          // valid为true:表单校验通过
          if (valid) {
            // 发送post请求
            this.$http.post('/login', this.form).then((res) => {
              const { code, message, token } = res
              //判断用户是否正确
              if (code == 201) {
                //将token放入localStorage,放在客服端中
                localStorage.setItem('token', token)
                //登录成功跳转到后台的首页
                this.$router.replace('/')
                //console.log(window.localStorage)
                this.$message.success(message)
              } else {
                //返回错误信息
                this.$message.error(message)
              }
            })
          }
        })
      }
    },
    //重置表单
    reset() {
      this.$refs.loginForm.resetFields()
    },
  },
}
</script>

<style>
.login-wrap {
  display: flex;
  height: 100vh;
  background-color: #294669;
  background-image: url('../assets/images/bg1.jpg');
  align-items: center;
  justify-content: center;
}
.container {
  width: 450px;
  height: 270px;
  background-color: rgba(255, 255, 255);
}
.login-title {
  text-align: center;
}
.container .avatar-box {
  width: 130px;
  height: 130px;
  border: 1px solid #fff;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -170%);
}
.container .avatar-box img {
  width: 130px;
  height: 130px;
  border-radius: 50%;
}
</style>
